<template>
	<view>
		<cu-custom bgColor="bg-blue" isBack>
			<block slot="content">数据导出</block>
		</cu-custom>

		<view class="content">
			<view class="cu-bar bg-white solid-bottom">
				<view class="action">
					<text class="cuIcon-title text-blue"></text>数据操作
				</view>
			</view>

			<view class="padding flex flex-direction">
				<button class="cu-btn bg-blue lg" @tap="getData">导出数据</button>
			</view>
			
			
			<view class="padding flex flex-direction margin-top">
				<button class="cu-btn bg-red lg" @tap="clearData">清除所有数据</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {

			}
		},
		methods: {
			getData() {
				plus.sqlite.selectSql({
					name: 'express',
					// sql: 'select * from express where  type = "box" and status = 1 LIMIT 2 ORDER BY scanTime DESC;',
					//1584264443480
					//1584288000000
					// sql: 'select * from express where  status = 1 ',//  ORDER BY "scanTime" DESC',
					sql: "SELECT express as '单号',  substr(datetime(scanTime/1000,'unixepoch'),0,20) as '时间', CASE type WHEN 'box' THEN '打包'  WHEN 'unbox' THEN '拆包' ELSE '拣件' END  as '工作类型' ,uuid as '设备号'  FROM express",
					//sql: 'select * from express where  type = "box" and status = 1 and scanTime > "${this.nowTime}"   ORDER BY scanTime DESC;',
					success: (data) => {
						console.log('selectSql success: ');
						uni.showToast({
							title:'导出成功'
						})
						// this.lists = data
						// console.log(JSON.stringify(data));
						let worksheet = "sheet1";

						let str = '<tr><td>单号</td><td>时间</td><td>工作类型</td><td>设备号</td></tr>';

						for (let i = 0; i < data.length; i++) {
							str += '<tr>';
							for (let item in data[i]) {
								//增加\t为了不让表格显示科学计数法或者其他格式
								str += `<td>${ data[i][item] + '\t'}</td>`;
							}
							str += '</tr>';
						}

						console.log(str);

						let template =
							`<html xmlns:o="urn:schemas-microsoft-com:office:office" 
							xmlns:x="urn:schemas-microsoft-com:office:excel" 
							xmlns="http://www.w3.org/TR/REC-html40">
							<head><!--[if gte mso 9]><xml encoding="UTF-8"><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
							  <x:Name>${worksheet}</x:Name>
							  <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
							  </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
							  </head><body><table>${str}</table></body></html>`;
						//下载模板
						this.saveExcel(template);
					},
					fail: function(e) {
						console.log('selectSql failed: ' + JSON.stringify(e));
					}
				});
			},
			saveExcel: function(urls) {
				var _this = this
				console.log(JSON.stringify(urls));
				plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
					console.log("requestFileSystem");
					// 创建文件夹
					fs.root.getDirectory('EXCEL', {
						create: true
					}, function(dirEntry) {
						console.log("getDirectory");
						// 创建文件
						dirEntry.getFile(_this.getCurrentDate(2)+'-data.xls', {
							create: true
						}, function(fileEntry) {
							console.log("getFile");
							fileEntry.createWriter(function(writer) {
								console.log("createWriter");
								// console.log(JSON.stringify(writer));
								writer.onwrite = function(e) {
									console.log("Write data success!");
								};
								// writer.write('1111111')
								// 写入内容;
								writer.write(urls);
								writer.onwriteend = function(e) {
									console.log('success');
								}
								console.log(_this.getCurrentDate(1));
							}, function(e) {
								console.log(e.message);
							});
						});
					});

				});
			},
			getCurrentDate(format) {
				var now = new Date();
				var year = now.getFullYear(); //得到年份
				var month = now.getMonth(); //得到月份
				var date = now.getDate(); //得到日期
				var day = now.getDay(); //得到周几
				var hour = now.getHours(); //得到小时
				var minu = now.getMinutes(); //得到分钟
				var sec = now.getSeconds(); //得到秒
				month = month + 1;
				if (month < 10) month = "0" + month;
				if (date < 10) date = "0" + date;
				if (hour < 10) hour = "0" + hour;
				if (minu < 10) minu = "0" + minu;
				if (sec < 10) sec = "0" + sec;
				var time = "";
				//精确到天
				if (format == 1) {
					time = year + "-" + month + "-" + date;
				}
				//精确到分
				else if (format == 2) {
					time = year + "-" + month + "-" + date + " " + hour + ":" + minu + ":" + sec;
				}
				return time;
			},
			clearData(){
				uni.showModal({
					title: '提示',
					content: '确定要删除吗? 此操作不可逆',
					success: res => {
						if (res.confirm) {
							plus.sqlite.executeSql({
								name: 'express',
								// sql: `update express set status = 0 where express = ${e.currentTarget.dataset.express}`,
								sql: `delete from express`,
								success: (e) => {
									console.log('executeSql success!');
									uni.showToast({
										title:"清除成功",
										icon:"none"
									})
								},
								fail: function(e) {
									console.log('executeSql failed: ' + JSON.stringify(e));
								}
							});
							uni.showToast({
								title:'清除成功'
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
				
			}
		}
	}
</script>

<style>

</style>
